package client;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import database.Base;

public class Client implements KeyListener, ActionListener {
	private Socket socket;
	private BufferedReader reader;
	private BufferedWriter writer;
	public static int SERVER_PORT;
	public static int ISERVER;

	private Base base;
	private JFrame frameJF;
	private JLabel serverJL, productNameJL, quantityJL, timeJL;
	private JComboBox serverJCB, productNameJCB;
	private JTextField quantityJTF, timeJTF;
	private JButton registerJB;
	private JTextArea infoJTA;
	private JScrollPane infoJSP;

	public Client() {

		base = new Base();
		base.open();

		frameJF = new JFrame("Client");
		frameJF.setSize(300, 400);
		frameJF.setLayout(null);
		frameJF.setResizable(false);

		serverJL = new JLabel("Server");
		serverJL.setSize(100, 50);
		serverJL.setLocation(20, 10);
		frameJF.add(serverJL);

		serverJCB = new JComboBox();
		serverJCB.setSize(150, 20);
		serverJCB.setLocation(100, 25);
		serverJCB.addActionListener(this);

		for (int i = 1; i <= 5; i++) {
			serverJCB.addItem("Server " + i);
		}

		frameJF.add(serverJCB);

		productNameJL = new JLabel("Mat hang");
		productNameJL.setSize(100, 50);
		productNameJL.setLocation(20, 35);
		frameJF.add(productNameJL);

		productNameJCB = new JComboBox();
		productNameJCB.setSize(150, 20);
		productNameJCB.setLocation(100, 50);

		try {
			ResultSet rS = base.getCon().createStatement()
					.executeQuery("select ProductName from Product1");

			while (rS.next()) {
				productNameJCB.addItem(rS.getString(1));
			}

			base.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		frameJF.add(productNameJCB);

		quantityJL = new JLabel("So luong");
		quantityJL.setSize(100, 50);
		quantityJL.setLocation(20, 60);
		frameJF.add(quantityJL);

		quantityJTF = new JTextField();
		quantityJTF.setSize(150, 20);
		quantityJTF.setLocation(100, 75);
		quantityJTF.addKeyListener(this);
		frameJF.add(quantityJTF);

		timeJL = new JLabel("Thoi gian");
		timeJL.setSize(100, 50);
		timeJL.setLocation(20, 85);
		frameJF.add(timeJL);

		timeJTF = new JTextField();
		timeJTF.setSize(150, 20);
		timeJTF.setLocation(100, 100);
		timeJTF.addKeyListener(this);
		timeJTF.setEditable(false);
		frameJF.add(timeJTF);

		new Thread(new Runnable() {

			public void run() {
				while (true) {
					try {
						timeJTF.setText(getDateTime());
						Thread.sleep(1000);
					} catch (InterruptedException e) {
					}
				}
			}
		}).start();

		registerJB = new JButton("Dang ky");
		registerJB.setSize(230, 25);
		registerJB.setLocation(20, 130);
		registerJB.addActionListener(this);
		frameJF.add(registerJB);

		infoJTA = new JTextArea();
		infoJSP = new JScrollPane(infoJTA,
				JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
				JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		infoJSP.setLocation(5, 170);
		infoJSP.setSize(275, 180);
		frameJF.add(infoJSP);

		frameJF.setVisible(true);
	}

	private String getDateTime() {
		// TODO Auto-generated method stub
		DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
		Date date = new Date();

		return dateFormat.format(date);
	}

	public void write(String message) {
		try {
			writer.write(message);
			writer.newLine();
			writer.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String read() {
		try {
			return reader.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return "";
		}
	}

	private String getResult(int iServer, String[] dataStrE) {
		base.open();

		String resultStr = "";
		ResultSet rS;

		try {
			rS = base.getCon().createStatement()
					.executeQuery("select * from Product" + iServer);

			while (rS.next()) {
				if (dataStrE[0].equals(rS.getString(1))) {
					if (Integer.parseInt(dataStrE[1]) <= Integer.parseInt(rS
							.getString(2))) {
						resultStr = "Dang ky thanh cong";

						for (int i = 1; i <= 5; i++) {
							base.getCon()
									.createStatement()
									.executeUpdate(
											"update Product"
													+ i
													+ " set Quantity = Quantity - "
													+ dataStrE[1]
													+ " where ProductName = '"
													+ dataStrE[0] + "'");
						}
					} else {
						resultStr = "Dang ky that bai. \nSo luong mat hang nay khong du.";
					}

					break;
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		base.close();
		return resultStr;
	}

	public static void main(String[] args) {
		new Client();
		// String dataStr = "A|3|04-Dec";
		//
		// String[] dataStrE = dataStr.split("[|]");
		//
		// client.write("Client?" + dataStr);
		// client.write("Client?" + dataStr);
	}

	public void keyPressed(KeyEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		if (e.getSource() == this.quantityJTF) {
			try {
				Integer.parseInt(this.quantityJTF.getText());
			} catch (NumberFormatException n) {
				this.quantityJTF.setText("");
			}
		}
	}

	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if (e.getSource() == this.serverJCB) {
			String server = (String) this.serverJCB.getSelectedItem();
			Client.ISERVER = server.charAt(7) - 48;
			Client.SERVER_PORT = Client.ISERVER + 2010;

			try {
				this.socket = new Socket("localhost", Client.SERVER_PORT);
				reader = new BufferedReader(new InputStreamReader(
						this.socket.getInputStream()));
				writer = new BufferedWriter(new OutputStreamWriter(
						this.socket.getOutputStream()));
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

		}

		if (e.getSource() == this.registerJB) {
			if (!this.quantityJTF.getText().equals("")) {
				String dataStr = (String) this.productNameJCB.getSelectedItem()
						+ "|" + this.quantityJTF.getText() + "|"
						+ this.timeJTF.getText();

				String[] dataStrE = dataStr.split("[|]");

				this.write("Client?" + dataStr + "&" + Client.SERVER_PORT + "&"
						+ 1);

				String inStr = this.read();

				this.write("Client " + (inStr.split("[|]")[3].charAt(7) - 48)
						+ "?" + dataStr);

				String oldInfo = this.infoJTA.getText() + "\n" + "->\n";
				this.infoJTA.setText(oldInfo
						+ this.getResult(ISERVER, dataStrE));
			} else {
				JOptionPane.showConfirmDialog(this.frameJF,
						"Vui long nhap so luong !", "Thong bao",
						JOptionPane.PLAIN_MESSAGE, JOptionPane.ERROR_MESSAGE);
			}
		}
	}
}
